﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.Configuration;
using DotNETX.Version.IniVersionInfo;

namespace DotNETX.Version
{
    public class VersionClient : DotNETX.CommonWcfClient.CommonClient<IVersionService>
    {
        public const string CONFIG_KEY_VERSIONINI_LOCATION = "DotNETX.Version.VersionClient.VersionIniLocation";

        public VersionClient() : base()
        {
        }

        public VersionClient(string configName, string endpointAddress)
            : base(configName, endpointAddress)
        {
            
        }

        public VersionClient(Binding binding, string endpointAddress)
            : base(binding, new System.ServiceModel.EndpointAddress(endpointAddress))
        {
        }

        public VersionInfo GetLatestVersion()
        {
            return Proxy.GetLatestVersion();
        }

        public bool SetCurrentVersion(VersionInfo versionInfo)
        {
            return Proxy.SetCurrentVersion(versionInfo);
        }

        public VersionInfo GetLocalVersion()
        {
            string configPath = TryGetAppSetting(this.GetType(), CONFIG_KEY_VERSIONINI_LOCATION);
            string path = VersionInfoUtils.LocateVersionIni(this.GetType(), configPath);
            return VersionInfoUtils.ReadVersionInfo(path);
        }

        public static VersionClient Create(string ip, int port, string protocal = "net.tcp", string catalog = "DotNETX.Version.VersionService", string configName = "DotNETX.Version.VersionService")
        {
            return new VersionClient(configName, string.Format("{2}://{0}:{1}/{3}", ip, port, protocal, catalog));
        }

        private static string TryGetAppSetting(Type type, string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(type.Assembly.Location);
            if (config.AppSettings.Settings.AllKeys.Contains(key))
            {
                return config.AppSettings.Settings[key].Value;
            }
            else
            {
                return ConfigurationManager.AppSettings[key];
            }
        }
    }
}
